package com.nzx.general.excel.controller;

import com.nzx.common.exception.BizException;
import com.nzx.common.result.ApiResult;
import com.nzx.common.result.ResultCommon;
import com.nzx.general.excel.util.ExcelValidateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 功能描述：通用Excel服务接口
 *
 * @author nzx
 * @date 2021/11/7 14:36:38
 */
@RestController
@RequestMapping("/api/common/excel")
@Api(tags = "通用Excel服务接口")
public class ExcelController {


    @GetMapping("/message")
    @ApiOperation(value = "获取信息",httpMethod = "GET")
    public ApiResult getMessage(){

        return ResultCommon.doSuccess("Excel测试信息成功！");
    }

    @GetMapping(value = "/excelModelExport", produces = "application/json;charset=utf-8")
    @ApiOperation("Excel模板导出接口")
    public void excelModelExport(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("会员信息");
        // 设置要导出的文件的名字
        String fileName = "会员信息导入模板" + ".xls";
        String[] headers = {"姓名", "手机号", "开始时间（格式：2020-01-01）", "结束时间（格式：2020-01-01）", "余额（单位为元，格式：整数或两位小数）", "备注（非必填）"};

        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        // 在excel表中添加表头
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
            //单元格内容居中
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cell.setCellStyle(cellStyle);
        }
        //设置列宽
        sheet.setColumnWidth(0, headers[0].getBytes().length*2*300);
        sheet.setDefaultColumnStyle(0,cellStyle);
        sheet.setColumnWidth(1, headers[1].getBytes().length*2*300);
        sheet.setDefaultColumnStyle(1,cellStyle);
        sheet.setColumnWidth(2, headers[2].getBytes().length*2*130);
        sheet.setDefaultColumnStyle(2,cellStyle);
        sheet.setColumnWidth(3, headers[3].getBytes().length*2*130);
        sheet.setDefaultColumnStyle(3,cellStyle);
        sheet.setColumnWidth(4, headers[4].getBytes().length*2*130);
        sheet.setDefaultColumnStyle(4,cellStyle);
        sheet.setColumnWidth(5, headers[5].getBytes().length*2*250);
        sheet.setDefaultColumnStyle(5,cellStyle);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition",
                "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    @PostMapping(value = "/importExcel", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "Excel导入", httpMethod = "POST")
    public ApiResult<Boolean> importExcel(@RequestParam MultipartFile file) throws Exception {
        if(!file.isEmpty()){
            if(ExcelValidateUtil.checkExcelFileType(file)){
                return ResultCommon.doSuccess("文件上传成功",1);
            }else{
                throw new BizException("上传文件格式错误");
            }
        }else{
            throw new BizException("未发现上传文件");
        }
    }
}
